import json
import random
import time
import redis
import requests
from flask import Blueprint, send_file, make_response, redirect
from flask_restful import Resource
from ronglian_sms_sdk import SmsSDK
from tools.my_jwt import jj
from app import db
from tools.captcha.captcha import captcha
from tools.comm import send_message , get_ali_object
from tools.myredis import r
from application.models.users.user import SfLogin
from application.models.users.user import *
from flask import Blueprint,request,jsonify
user_blue = Blueprint("userblue",__name__)
from captcha.image import ImageCaptcha
# @user_blue.route('/text')
# def get():
#     return jsonify({'code':200,'msg':'mes'})

@user_blue.route('/getcode')
def get_img():
    name,text,img=captcha.generate_captcha()
    uuid=request.args.get('uuid')
    r.str_add(uuid,text)
    cls = redis.Redis(host='127.0.0.1')
    print(">>>>>>>>>>>>>>>>",cls.get(uuid))
    res=make_response(img)
    res.headers['Content-Type']="image/jpg"
    return res

@user_blue.route("/sendSmsCode",methods=["POST"])
def sendSmsCode():
    data = request.data
    # 获取3个参数
    if data:
        data = json.loads(data)
        uuid = data['uuid']
        piccode = data['piccode']
        print(piccode,'>>>>>>>>>>>>>>>>')
        mobile = data['mobile']
        value = r.str_get(uuid)
        value1 = value.decode()
        print(value1)
        if value:
            if piccode.lower()==value1.lower():
                mcode = r.str_get(mobile)
                if mcode:
                    return jsonify({'code':10012,'msg':'一分钟内不能重复发'})
                scode = random.randint(10000,99999)
                flag = send_message(mobile,scode)
                if flag:
                    r.str_setex(mobile,scode,60)
                    r.del_key(uuid)
                    return jsonify({'code':200,'msg':'发送成功'})
                else:
                    return jsonify({'code':10013,'msg':'发送验证码错误'})
            else:
                return jsonify({'code':10011,'msg':'图片验证码错误'})
        else:
            return jsonify({'code':10010,'msg':'图片验证码不存在'})

import time
# 发送短信接口
@user_blue.route("/login",methods=['POST'])
def login():
    data = request.data
    if data:
        data = json.loads(data)
        mcode = data["code"]
        mobile = data["mobile"]
        code = r.str_get(mobile)
        if code:
            if int(code)==int(mcode):
                user = User.query.filter(User.mobile==mobile).first()
                if user:
                    r.del_key(mobile)
                else:
                    u = User(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                    user = User.query.filter(User.mobile==mobile).first()
                token = str(random.randint(100,1000))
                return jsonify({"code":200,"msg":"发送成功","token":token,"userid":user.id})
        else:
            return jsonify({"code":10021,"mes":"验证码不存在"})
    else:
        return jsonify({"code":10020,"mes":"数据不完整"})

# 获取weibo地址
@user_blue.route('/sf_login')
def getwburl():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({"code":200,"url":url})

# weibo回调接口
@user_blue.route('/user/weiboCallback/')
def weiboCallback():
    # 获取code
    code = request.args.get("code")
    # 向access_token接口发送post请求
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 获取token和uid
    message = json.loads(res.text)
    token = message['access_token']
    uid = message['uid']
    # 查询数据库中是否存在，如果存在用户信息生成jwt token 返回
    sql = 'select user.id from user inner join sf_login on user.id=sf_login.userid where sf_login.uid=%s'%(uid)
    user = db.session.execute(sql)
    if user:
        for i in user:
            data = {'data':{'userid':i[0],'exp':int(time.time())}}
            token = jj.jwt_encode(data)
            return redirect("http://localhost:8080/#/updateToken?userid=" + str(i[0]) + "&token=" + token)
    # 不存在跳转到vue绑定页面，token uid 传递过去
    return redirect("http://localhost:8080/#/binMobile?uid="+uid+"&token="+token)

# 绑定手机号
@user_blue.route('/binMobile',methods=['POST'])
def binMobile():
    data = json.loads(request.data)
    mobile = data['mobile']
    uid = data['uid']
    token = data['token']
    print(mobile,'>>>>>>>>>>>>>>>>>>>>>>>>>..')
    # 先查询用户表，如果手机号存在，获取userid,写入三方登录表，生成token返回
    user = User.query.filter(User.mobile==mobile).first()
    print(user)
    if not user:
        # 添加用户
        u = User(mobile=mobile,nikename=mobile)
        print(u)
        db.session.add(u)
        db.session.commit()
        # 获取用户信息
        user = User.query.filter(User.mobile==mobile).first()
    sfuser = SfLogin(userid=user.id, webfrom='wb', uid=uid, token=token)
    db.session.add(sfuser)
    db.session.commit()
    # 如果不存在，写入user表
    # 获取userid,写入三方登录表，生成token返回
    data = {'data':user.id,'exp':int(time.time())}
    token = jj.jwt_encode(data)
    return jsonify({'userid':str(user.id),'token':token})


# 测试
@user_blue.route("/test")
def test():
    orderon = 12345566
    pay = get_ali_object()
    query_params = pay.direct_pay(
        subject='test' + "充值服务",  # 商品简单描述
        out_trade_no=orderon,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(1.00),  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })

@user_blue.route("/callback")
def callback():
    #接受参数
    data = request.args
    datames = {k:v for k,v in data.items()}
    #删除字典中key为sign的记录
    sign = datames.pop("sign")
    #鉴权 订单号 流水号
    pay = get_ali_object()
    flag = pay.verify(datames,sign)
    if flag == True:
        #支付宝流水号
        transaction_no = datames["trade_no"]
        #订单号
        order_no = datames["out_trade_no"]
        #事务处理
        try:
            #订单号更新表
            record = VipRecord.query.filter(VipRecord.order_no==order_no).first()
            # sql = "select * from vip_record where order_no = '%s'"%(order_no)
            # res = db.session.execute(sql)
            # record = res.fetchone()
            # print(record)
            # #print(record,status)
            # return "ok"
            record.status=2
            record.transaction_no=transaction_no
            db.session.add(record)
            #更新用户表
            User.query.filter(User.id == record.userid).update({"level":2})
            #更新vip表
            vip = Vip.query.filter(Vip.userid==record.userid,status=1).first()
            if vip is not None:
                #结束时间+购买年限
                etime = vip.e_time.split("-")
                tyear = int(etime[0])+int(record.year)
                yearstr="-"
                etime[0] = str(tyear)
                retime = yearstr.join(etime)
                vip.e_time= retime
                db.session.add(vip)
            else:
                nowyear = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%m:%s")
                etime = nowyear.split("-")
                tyear = int(etime[0]) + int(record.year)
                etime[0] = str(tyear)
                yearstr = "_"
                retime = yearstr.join(etime)
                # print(retime)
                # year = 365*int(record.year)
                # retime = datetime.datetime.now()+datetime.timedelta(days=year)
                vip = Vip(Userid=record.userid,s_time=datetime.datetime.now(),e_time=retime)
                db.session.add(vip)
            db.session.commit()
        except:
            db.session.rollback()
    else:
        print("鉴权失败")
    return "ok"

#添加课程使用，获取标签，分类，类别
@user_blue.route("/getTags")
def getTags():
    tags = Tags.query.all()
    tagsList = [{"id":i.id,"name":i.name} for i in tags]
    types = Ctype.query.all()
    typesList = [{"id":i.id,"name":i.name} for i in types]
    ctype = CourseType.query.all()
    clist = [{"id":i.id,"name":i.name} for i in ctype]
    return jsonify({"code":200,"tags":tagsList,"types":typesList,"clist":clist})


# #类别
# @user_blue.route("/ctype")
# def ctype():
#     ctypelist = []
#     # 获取缓存中数据
#     r.del_key("ctype")
#     ctype = r.get_str("ctype")
#     # 判断是否存在
#     if ctype:
#         ctypelist = json.loads(ctype)
#     else:
#         sql = Ctype.query.all()
#         for i in sql:
#             d = {"name":i.name}
#             ctypelist.append(d)
#         # 存入缓存
#         r.set_str("ctype", json.dumps(ctypelist))
#     return ctypelist
#
#
# # 标签
# def getTaglist():
#     taglist = []
#     r.del_key("tage")
#     tag = r.get_str("tage")
#     if tag:
#         taglist = json.loads(tag)
#     else:
#         sql = Tags.query.all()
#         for i in sql:
#             d = {"name":i.name}
#             taglist.append(d)
#         r.set_str("tage", json.dumps(taglist))
#     return taglist
#
# #分页
# @user_blue.route("/getHomeGourse")
# def getHomeGourse1():
#     # 获取类型
#     ctypelist = ctype()
#     # 获取标签
#     taglist = getTaglist()
#
#     # 获取当前页面
#     page = request.args.get("page")
#     # 获取查询条件
#     typeid = request.args.get("type")
#     tagid = request.args.get("tagid")
#     online = request.args.get("online")
#     # 排序条件
#     orderbyid = request.args.get("orderbyid")
#     print(tagid)
#
#     where = ""
#     if int(typeid) > 0:
#         where = where + " and c.ctype=" + typeid
#
#     if int(online) > 0:
#         where = where + " and c.views=" + online
#
#     # res = db.session.execute("select * from user where id=1")
#     # print(res.fetchall())
#     # print(res.fetchone())
#
#     if int(tagid) > 0:
#         tsql = "select count(c.id) as tcount from course as c inner join course_tag as cl on cl.coursesid=c.id  where cl.tagid=" + tagid
#         sql = "select * from course as c inner join course_tag as cl on cl.coursesid=c.id  where cl.tagid=" + tagid
#     else:
#         sql = "select * from course as c where 1=1"
#         tsql = "select count(c.id) as tcount from course as c  where 1=1"
#
#     if where:
#         sql = sql + " " + where
#         tsql = tsql + " " + where
#
#     if int(orderbyid) > 0:
#         if int(orderbyid) == 1:
#             sql = sql + " order by c.id desc"
#         else:
#             sql = sql + " order by c.is_publish desc"
#
#     # 查询总共有多少条
#     tsql = db.session.execute(tsql)
#     print(tsql)
#     total = 0
#     for i in tsql:
#         total = i[0]
#
#     page_size = 2
#     start = (int(page) - 1) * page_size
#     clist = sql + " limit %d,%d" % (start, page_size)
#     clist = db.session.execute(clist)
#     # courselist.fetchall()
#     courselist = []
#     for i in clist:
#         d = {
#             "id":i[0],
#             "create_time":i[1],
#             "update_time":i[2],
#             "name":i[3],
#             "url":i[4],
#             "descrip":i[5],
#             "tcount":i[6],
#             "views":i[7],
#             "is_publish":i[8],
#             "ctype":i[9]
#         }
#         courselist.append(d)
#
#     return jsonify({"code": 200, "tlist": ctypelist, 'taglist': taglist, 'clist': courselist, "total": total,
#                     "page_size": page_size})